import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';


import DropZoneWidget from "../../widgets/DropZoneWidget";
import ExpenseCollectionView from './ExpenseCollectionView.js';
import ExpenseFileCollectionView from "./ExpenseFileCollectionView";


import { formatAmount } from '../../math.js';


const ExpenseTableView = Mn.View.extend({
    template: require('./templates/ExpenseTableView.mustache'),
    regions: {
       lines: {
           el: 'tbody.lines',
           replaceElement: true
       },
       files: {
           el: 'tbody.files',
           replaceElement: true,
       },
       dropzone: '.dropzone',
    },
    ui:{
        add_btn: 'button.add',
    },
    events: {
        'click @ui.add_btn': 'onAdd',
    },
    childViewTriggers: {
        'line:edit': 'line:edit',
        'line:delete': 'line:delete',
        'line:duplicate': 'line:duplicate',
        'bookmark:add': 'bookmark:add',
        'file:delete': 'attachment:delete',
        'file:link_to_expenseline': 'attachment:link_to_expenseline',
    },
    childViewEvents: {
        'file:new_expense': 'onAddWithAttachment',
    },
    collectionEvents: {
        'change:category': 'render',
    },
    initialize(){
        var channel = Radio.channel('facade');
        this.totalmodel = channel.request('get:totalmodel');

        this.categoryId = this.getOption('category').value;
        this.listenTo(
            channel,
            'change:lines_' + this.categoryId,
            this.render.bind(this)
        );
    },
    isCollectionEmpty(){
        return this.collection.find(
            x => x.get('category') == this.categoryId
        ) === undefined;
    },
    includesTvaOnMargin() {
        let that = this;
        let result = this.collection.find(function(expense) {
            return expense.hasTvaOnMargin() && expense.get('category') == that.categoryId;
        });
        return result;
    },
    isAchat(){
        return this.getOption('category').value==2;
    },
    canValidateAttachments(){
        return ! _.isUndefined(
            Radio.channel('config').request('get:actions').justify
        );
    },
    templateContext(){
        let is_empty = this.isCollectionEmpty();
        return {
            category: this.getOption('category'),
            edit: this.getOption('edit'),
            is_achat: this.isAchat(),
            includes_tva_on_margin: this.includesTvaOnMargin(),
            total_ht: formatAmount(this.totalmodel.get('ht_' + this.categoryId)),
            total_tva: formatAmount(this.totalmodel.get('tva_' + this.categoryId)),
            total_ttc: formatAmount(this.totalmodel.get('ttc_' +this.categoryId)),
            is_empty: is_empty,
            is_not_empty: ! is_empty,
            can_validate_attachments: this.canValidateAttachments(),
        };
    },
    onAdd(){
        this.triggerMethod(
            'line:add',
            this,
            {category: this.getOption('category').value},
        );
    },
    onAddWithAttachment(attachment){
        this.triggerMethod(
            'line:add',
            this,
            {
                category: this.getOption('category').value,
                files: [attachment.id],
            },
            true,
        );
    },
    onRender(){
        let edit = this.getOption('edit');
        this.showChildView(
            'lines',
            new ExpenseCollectionView({
                collection: this.collection,
                category: this.getOption('category'),
                edit: this.getOption('edit'),
                can_validate_attachments: this.canValidateAttachments(),
            })
        );
        this.showChildView(
            'files',
            new ExpenseFileCollectionView({
                collection: this.getOption('filesCollection'),
                is_achat: this.isAchat(),
                edit: edit,
                can_validate_attachments: this.canValidateAttachments(),
            })
        );
        if (edit) {
            this.showChildView(
                'dropzone',
                new DropZoneWidget({})
            );
        }
    },
});
export default ExpenseTableView;
